<template>
	<view class="container">
		<view class="search-box">
			<uni-search-bar @input="onSearchInput" v-model="searchKeyword" placeholder="订单号/申请人/物品名称" />
		</view>
		<view class="filter-container">
			<uni-segmented-control :current="status" :values="items" :style-type="'button'" :active-color="'#18bc37'"
				@clickItem="onClickItem" class="segmented-control" />
		</view>
		<!-- 列表区域 -->
		<scroll-view scroll-y="true" class="list-container" @refresherrefresh="handleRefresh"
			@scrolltolower="handleLoadMore" :refresher-enabled="true" :refresher-triggered="refreshing"
			:scroll-with-animation="true" :enable-back-to-top="true">

			<view v-if="loading && recordList.length === 0" class="loading">
				<text>加载中...</text>
			</view>
			<view v-if="recordList.length === 0 && !loading" class="empty-state">
				<image src="/static/avatar/empty.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">没有记录</text>
			</view>

			<view v-for="(record, index) in recordList" :key="index">
				<uni-card :is-shadow="true" margin="20rpx 0">
					<template v-slot:title>
						<view class="card-header">
							<text class="time">订单号：{{ record.order_id }}</text>
							<!-- <text class="time"> {{ formatDate(record.create_date) }}</text> -->
							<uni-tag :text="getStatusText(record.status)"
								:type="statusTypeMap[record.status] || 'default'"></uni-tag>
						</view>
					</template>

					<uni-list>
						<uni-list-item :border="false">
							<template v-slot:body>
								<view class="goods-container">
									<!-- 商品信息 -->
									<view class="goods-info">
										<image class="goods-thumb" :src="record.goods.thumb || defaultThumb"
											mode="aspectFill" @click="previewImage(record.goods.thumb)" />
										<view class="goods-content">
											<view class="goods-title">
												<text class="">{{ record.goods.name }}</text>
												<uni-tag class="tag" :text="getStatusText2(record.goods.status)"
													:type="statusTypeMap2[record.goods.status] || 'default'"></uni-tag>
											</view>
											<view class="goods-desc">
												<text class="desc-text"
													v-if="record.goods.brand">{{ record.goods.brand }}</text>
												<text class="desc-text"
													v-if="record.goods.model">{{ record.goods.model }}</text>
											</view>
											<view class="goods-desc">{{ record.goods.desc }}</view>
											<view class="goods-count">领取数量：{{ record.goods._cartNumber }}</view>
										</view>
									</view>

									<!-- 底部操作按钮 -->
									<view class="action-buttons"
										v-if="record.status === 1 && record.goods.status === 0">
										<button class="action-btn return"
											@tap="handleReport(record.goods, record._id, 4)">归还</button>
										<button class="action-btn damage"
											@tap="handleReport(record.goods, record._id, 2)">报失</button>
										<button class="action-btn loss"
											@tap="handleReport(record.goods, record._id, 3)">报损</button>
									</view>
								</view>
							</template>
						</uni-list-item>
					</uni-list>

					<template v-slot:actions>
						<view class="action-buttons" >
							<button class="action-btn view-btn" @tap="viewDetail(record._id)">查看详情</button>
							<button class="action-btn cancel-btn" v-if="record.status === 0" @tap="handleCancel(record, 3)">取消申请</button>
						</view>
						<view class="card-footer" v-if="record.status === 1 || record.status === 2">
							<view class="user">
								<text class="user-text">审核人：{{record.approve_name}}</text>
								<text class="">时间：{{record.approve_date}}</text>
							</view>
							<view class="refuse" v-if="record.status === 1">
								<text class="refuse-text">审核备注：{{record.note}}</text>
							</view>
							<view class="refuse" v-if="record.status === 2">
								<text class="refuse-text">驳回理由：{{record.refuse}}</text>
							</view>

						</view>
					</template>
				</uni-card>
			</view>
			<!-- 加载状态提示 -->
			<uni-load-more :status="loadStatus" :content-text="{
			        contentdown: '上拉显示更多',
			        contentrefresh: '正在加载...',
			        contentnomore: '没有更多数据了'
			      }" v-if="recordList.length > 0" />
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchKeyword: '',
				defaultThumb: '/static/avatar/empty.png',
				recordList: [],
				status: 0,
				statusTypeMap: {
					0: 'warning', // 待核准
					1: 'success', // 已核准
					2: 'error', // 已驳回
					3: 'default' // 已取消
				},
				statusTypeMap2: {
					0: 'default', // 领用中
					1: 'success', // 归还
					2: 'warning', // 遗失
					3: 'error', // 损坏
					4: 'default', //归还，待审核
				},
				items: ['待核准', '已核准', '已驳回', '已取消'],
				loadStatus: 'more',
				currentPage: 1,
				pageSize: 10,
				// 防抖用的 timer
				searchTimer: null,
				total: 0,
				user_id: '',
				//新增
				loading: false,
				refreshing: false,
				isLoadMore: false
			}
		},
		computed: {
			// 计算加载状态
			loadingStatus() {
				if (this.loading) return 'loading';
				if (this.recordList.length >= this.total) return 'noMore';
				return 'more';
			}
		},
		mounted() {
			this.initData()
		},
		// onPullDownRefresh() {
		// 	this.handleRefresh();
		// },
		// 使用页面触底事件替代滚动事件
		// onReachBottom() {
		// 	this.handleLoadMore();
		// },
		methods: {
			async initData() {
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo?._id) {
					this.user_id = userInfo._id
					await this.fetchRecords()
				}
				//console.log('11111',this.recordList)
			},
			onSearchInput() {
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.initData();
				}, 1000)
			},
			// 修改状态切换处理
			onClickItem(e) {
				if (this.status !== e.currentIndex) {
					this.status = e.currentIndex;
					this.currentPage = 1;
					this.recordList = [];
					this.fetchRecords();
				}
			},
			// 修改后的刷新方法
			async handleRefresh() {
				this.refreshing = true;
				this.currentPage = 1;
				await this.fetchRecords();
				this.refreshing = false;
			},
			// 修改后的加载更多方法
			async handleLoadMore() {
				if (this.loadStatus === 'noMore' || this.isLoadMore || this.loading) return;
				this.isLoadMore = true;
				this.currentPage += 1;
				await this.fetchRecords(true);
				this.isLoadMore = false;
			},
			// 修改后的数据获取方法
			async fetchRecords(isLoadMore = false) {
				if (this.loading) return;
				this.loading = true;

				try {
					const params = {
						user_id: this.user_id,
						status: this.status,
						keyword: this.searchKeyword,
						page: this.currentPage,
						pageSize: this.pageSize
					};
					const goodsObj = uniCloud.importObject('goods');
					const res = await goodsObj.getGoodsRecord(params);
					if (res.code === 0) {
						this.total = res.total;
						if (isLoadMore) {
							this.recordList = [...this.recordList, ...res.data];
						} else {
							this.recordList = res.data;
						}
						this.loadStatus = this.recordList.length >= this.total ? 'noMore' : 'more';
					}
				} finally {
					this.loading = false;
				}
			},
			formatDate(dateStr) {
				return dateStr ? dateStr.replace('T', ' ').substr(0, 16) : ''
			},
			getStatusText(status) {
				const statusMap = {
					0: '待核准',
					1: '已核准',
					2: '已驳回',
					3: '已取消'
				}
				return statusMap[status] || '未知状态'
			},
			getStatusText2(status) {
				const statusMap = {
					0: '正常',
					1: '归还',
					2: '遗失',
					3: '损坏',
					4: '归还中'
				}
				return statusMap[status] || '未知状态'
			},
			handleReport(goods, recordid, type) {
				const obj = uniCloud.importObject('goods')
				const res = obj.updateGoodsRecordGoodsStatus({
					_id: recordid,
					data: {
						_id: goods._id,
						status: type,
						_cartNumber: goods._cartNumber
					}
				}).then(r => {
					if (r.code == 0) {
						uni.showToast({
							icon: "success",
							title: r.message
						})
						// 刷新页面数据（推荐方式）
						setTimeout(() => {
							this.initData();
							uni.hideLoading();
						}, 1000);
					}
				})
			},
			viewDetail(id) {
				uni.$router.to({
					url: '/pagesA/item/goods/detail', // 根据实际路由调整
					params: {
						_id: id
					}
				})
			},
			handleCancel(record, type) {
				const obj = uniCloud.importObject('goods')
				const res = obj.updateRecordStatus({
					_id: record._id,
					status: type,
					data: record.goods
				}).then(r => {
					// //console.log('111', r)
					if (r.code == 0) {
						uni.showToast({
							icon: "success",
							title: r.message
						})
						// 刷新页面数据（推荐方式）
						setTimeout(() => {
							this.initData();
							uni.hideLoading();
						}, 1000);
					}
				})
			},
			updateRecordStatus(recordId, status) {
				this.recordList = this.recordList.map(record => {
					if (record._id === recordId) {
						return {
							...record,
							status
						}
					}
					return record
				})
			},
			previewImage(url) {
				if (url) uni.previewImage({
					urls: [url]
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 在样式部分最前面添加颜色变量 */
	$primary-color: #2979ff;
	$danger-color: #e54d42;

	.container {
		padding: 20rpx;
		background: #f8f8f8;
		min-height: 100vh;
	}

	.goods-container {
		display: flex;
		flex-direction: column;
		padding: 20rpx 0;
	}

	.goods-info {
		display: flex;
		align-items: flex-start;

		.goods-thumb {
			width: 180rpx;
			height: 180rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
			flex-shrink: 0;
		}

		.goods-content {
			flex: 1;
			min-width: 0;
			width: 100%;

			.goods-title {
				font-size: 30rpx;
				color: #333;
				line-height: 1;
				font-weight: bold;
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;

				.tag {
					transform: scale(0.8);
					transform-origin: right center;
					margin-left: 20rpx;
					flex-shrink: 0;

					/* 如果需要更精确控制 */
					// ::v-deep .uni-tag--default {
					// 	height: 36rpx;
					// 	line-height: 36rpx;
					// 	padding: 0 12rpx;
					// 	font-size: 24rpx;
					// }
				}
			}

			.goods-desc {
				overflow: hidden;
				margin-top: 10rpx;
				display: flex;
				align-content: center;
				align-items: center;
				font-size: 24rpx;

				.desc-text {
					background-color: #FAEFF7;
					padding: 2rpx 10rpx;
					box-sizing: border-box;
					color: #e11d48;
					border-radius: 10rpx;
					margin-right: 15rpx;

				}
			}

			.goods-count {
				font-size: 26rpx;
				color: #007AFF;
			}
		}
	}

	/* 修改操作按钮样式 */
	.action-buttons {
		display: flex;
		justify-content: flex-end;
		margin-top: 0rpx;
		margin-bottom: 10rpx;
		gap: 20rpx;

		.action-btn {
			padding: 0 30rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			background: #f0f4f8;
			color: #333;
			border: none;
			transition: all 0.2s;

			&::after {
				border: none;
			}

			&.return {
				margin-top: 10rpx;
				background: #18bc37;
				color: #fff;
			}

			&.damage {
				margin-top: 10rpx;
				background: #f0ad4e;
				color: #fff;
			}

			&.loss {
				margin-top: 10rpx;
				background: #dd524d;
				color: #fff;
			}

			&.view-btn {
				background: #f0f4f8;
				color: $primary-color;
			}

			&.cancel-btn {
				background: #f0f4f8;
				color: $danger-color;
			}

			&:active {
				opacity: 0.8;
				transform: scale(0.98);
			}
		}
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 0;

		.time {
			font-size: 26rpx;
			color: #000000;
		}
	}

	.card-footer {
		padding-top: 10rpx;
		padding-bottom: 10rpx;

		border-top: 1rpx solid #eee;
		flex: 1;
		display: flex;
		flex-direction: column;

		.user {
			font-size: 26rpx;
			color: #000000;
			font-weight: bold;

			.user-text {
				padding-right: 50rpx;
			}
		}

		.refuse {
			flex: 1;
			flex-direction: row;
			padding-top: 10rpx;

			.refuse-text {
				color: #ff0000;
			}
		}
	}

	::v-deep .uni-list-item__container {
		padding: 0 !important;
	}

	.example {
		height: 100%;
		overflow-y: auto;
		padding: 15px;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 30rpx;
			color: #999;
			margin-top: 30rpx;
		}
	}

	.search-box {
		background: #fff;
		padding: 5rpx;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
	}

	.segmented-control {
		.uni-segmented-control__item {
			flex: 1;
			min-width: 160rpx; // 设置每个按钮的最小宽度
			margin: 0 10rpx; // 按钮之间留出间距
			border-radius: 40rpx;
			background-color: #f0f0f0;
			color: #666;
			transition: all 0.3s ease;

			&.uni-segmented-control__item--active {
				background-color: #18bc37;
				color: #fff;
			}
		}
	}

	.list-container {
		/* 修正高度计算 */
		height: calc(100vh - 380rpx);
		/* 根据实际布局调整 */
	}

	.loading {
		padding: 20rpx;
		text-align: center;
		color: #999;
	}
</style>